package com.fh.controller.app.appuser;

import java.awt.List;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fh.controller.base.BaseController;
import com.fh.entity.system.User;
import com.fh.service.system.appuser.LoginService;
import com.fh.service.system.appuser.RegisteredService;
import com.fh.service.system.redis.RedisService;
import com.fh.service.system.userassets.UserAssetsService;
import com.fh.util.Authentication;
import com.fh.util.Base64;
import com.fh.util.ClassNameUtil;
import com.fh.util.EncryptUtil;
import com.fh.util.HttpConfig;
import com.fh.util.StatusCode;
import com.fh.util.IpAddressUtils;
import com.fh.util.JsonStringUtil;
import com.fh.util.PageData;
import com.fh.util.SendSms;

import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;

@Controller
@RequestMapping(value="/exc/user")
public class Registered extends BaseController{
	@Resource(name="loginService")
	private LoginService loginService;
	
	@Resource(name="registeredService")
	private RegisteredService rService;

	
	@Resource(name="userassetsService")
	private UserAssetsService userassetsService;
	
    

	@Resource(name="redisService")
	private RedisService redis;
	
//	@SuppressWarnings("finally")
	@RequestMapping("/login/en")
	@ResponseBody 
    public String loginEN(HttpSession session,HttpServletRequest request) {
		System.out.println("gjyuhhjhhj");
		return "ABC";
	}
	
	@RequestMapping("/login/zh")
	@ResponseBody 
    public String loginCN(HttpSession session,HttpServletRequest request) {
		System.out.println("水电费的水电费");
		return "ABC";
	}

	@SuppressWarnings("finally")
	@RequestMapping(value=ClassNameUtil.login,produces =HttpConfig.CONTENT_TYPE_UTF8)
	@ResponseBody 
    public Object login(HttpSession session,HttpServletRequest request) {
		Object result ="";
		try {
			logBefore(logger, "开始调用登录接口");
			 PageData pd = new PageData();
			 Object parameter = pd.getParameters(request);
	         JSONObject jsonObject = JSONObject.fromObject(parameter);
	         String key1 = new String(EncryptUtil.Base64decode(jsonObject.getString("key1")));
	         String key2 =new String(EncryptUtil.Base64decode(jsonObject.getString("key2")));
	         String access_key = new String(EncryptUtil.Base64decode(jsonObject.getString("access_key")));
	         String sult =Base64.check(key1, key2);
	         if (sult.equals(access_key)) {
	        	 logBefore(logger, "接口校验成功");
		         String mobile_email = new String(EncryptUtil.Base64decode(jsonObject.getString("mobile_email")));
		         String password = new String(EncryptUtil.Base64decode(jsonObject.getString("password")));
		         String type = new String(EncryptUtil.Base64decode(jsonObject.getString("type")));
		         pd.put("mobile_email", mobile_email);
		        // pd.put("password", password);
		         //pd.put("password", new SimpleHash("SHA-1", pd.getString("mobile_email"), password).toString());
		         pd.put("password",EncryptUtil.AESEncode(password));
		         System.out.println(pd.getString("password"));
		         pd.put("type",type);
		         PageData list = rService.login(pd);
		         if(null != list){
                     java.util.List<PageData> listPagedata =new ArrayList<>(); 
                     listPagedata.add(list);
		        	 redis.setList(list.getString("USER_ID").toString(), listPagedata);
		        	 java.util.List<PageData> li = redis.getList(list.getString("USER_ID").toString(),PageData.class);
		        	 System.out.println(li);
		        	 result = JsonStringUtil.getJSONResult(StatusCode.SUCCESS,"登录成功",list.get("USER_ID"));
		         }else {
		        	 result = JsonStringUtil.getJSONResult(StatusCode.ERROR_USER,"登录失败","");
				}
		         System.out.println(mobile_email+ "" +password);
			} else {

				result= JsonStringUtil.getJSONResult(StatusCode.ERROR_INTERFACE,"接口校验失败","");
			}

		} catch (Exception e) {
			result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"服务器内部错误","");
			logger.error(e.toString(),e);
			e.printStackTrace();
		}finally{
	    	 return result.toString();
		}
    }
	
	
	/*
	 * 注册
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value=ClassNameUtil.registered,produces =HttpConfig.CONTENT_TYPE_UTF8)
	@ResponseBody
	public String registered(HttpServletRequest request) {
		Object result ="";
               
		try {
			logBefore(logger, "开始调用注册接口");
			 PageData pd = new PageData();
			 Object parameter = pd.getParameters(request);
			 JSONObject jsonObject = JSONObject.fromObject(parameter);
			 String res_type = new String(EncryptUtil.Base64decode(jsonObject.getString("res_type")));
	         String key1 = new String(EncryptUtil.Base64decode(jsonObject.getString("key1")));
	         String key2 = new String(EncryptUtil.Base64decode(jsonObject.getString("key2")));
	         String access_key = new String(EncryptUtil.Base64decode(jsonObject.getString("access_key")));
	         String sult = Base64.check(key1, key2);
	         if (sult.equals(access_key)) {       //接口校验
	        	 logBefore(logger, "接口校验成功");
				 String mobile_email = new String(EncryptUtil.Base64decode(jsonObject.getString("mobile_email")));
				 String password = new String(EncryptUtil.Base64decode(jsonObject.getString("password")));
					// String recommend_code = jsonObject.getString("recommend_code");
				 String type = new String(EncryptUtil.Base64decode(jsonObject.getString("type")));
				 pd.put("res_type", res_type);
				 pd.put("user_id", this.get32UUID());
	
					
				// pd.put("password", new SimpleHash("SHA-1", pd.getString("username"), pd.getString("password")).toString());
			     pd.put("type", type);
			     pd.put("ip", IpAddressUtils.INTERNET_IP);
			     pd.put("user_name", random());
			     pd.put("ROLE_ID", "b04e85d0a9514789b38b14b0d0392a02");
			     pd.put("password",EncryptUtil.AESEncode(password));
				 System.out.println(pd.getString("password"));
	             if(type.equals("0")){
	            	 pd.put("phone", mobile_email);
	            	 pd.put("email", "");
	             }else{
	               	 pd.put("email", mobile_email);
	            	 pd.put("phone", "");
	             }
			     PageData list = rService.query(pd);
			     Long ret= (Long) list.get("result");
			     System.out.println(ret);
			     if(ret==0){
			    	 rService.save(pd);
			    	 pd.put("ASSETS_ID", this.get32UUID());
			    	 rService.assets(pd);
			    	 result = JsonStringUtil.getJSONResult(StatusCode.SUCCESS,"注册成功","");
			     }else {
			    	 result = JsonStringUtil.getJSONResult(StatusCode.ERROR_USER,"该账户已被注册","");
				}
	         }else{
					result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"接口校验失败","");
	         }
	     
	} catch (Exception e) {
			result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"服务器内部错误","");
			logger.error(e.toString(),e);
			e.printStackTrace();
		}finally {
			return result.toString();
		}
	}
	
   public String random(){
	   String randomcode = "";
		for(int i=0;i<6;i++)
		{
			//52个字母与6个大小写字母间的符号；范围为91~96
			int value = (int)(Math.random()*58+65);
			while(value>=91 && value<=96)
				value = (int)(Math.random()*58+65);
			randomcode = randomcode + (char)value;
		}

	return randomcode;

   }

	
	
	/*
	 * 忘记密码
	 */
	@SuppressWarnings("finally")
    @RequestMapping(value=ClassNameUtil.forget_pwd,produces =HttpConfig.CONTENT_TYPE_UTF8)
	@ResponseBody
	public String forget_pwd(HttpServletRequest request){
		Object result ="";
		try {
			logBefore(logger, "开始调用忘记密码接口");
			PageData pd = new PageData();
			Object parameter = pd.getParameters(request);
			JSONObject jObject = JSONObject.fromObject(parameter);
	         String key1 = new String(EncryptUtil.Base64decode(jObject.getString("key1")));
	         String key2 = new String(EncryptUtil.Base64decode(jObject.getString("key2")));
	         String access_key = new String(EncryptUtil.Base64decode(jObject.getString("access_key")));
	         String sult = Base64.check(key1, key2);
	         if (sult.equals(access_key)) {
	        	 logBefore(logger, "接口校验成功");
	 	  		String mobile_email =new String(EncryptUtil.Base64decode(jObject.getString("mobile_email")));
		  		String password = new String(EncryptUtil.Base64decode(jObject.getString("password")));
		  		String type = new String(EncryptUtil.Base64decode(jObject.getString("type")));
		  		pd.put("mobile_email", mobile_email);
		  		//pd.put("password", password);
		  		pd.put("password",EncryptUtil.AESEncode(password));
		  		pd.put("type", type);
	            if(type.equals("0")){
	           	 pd.put("phone", mobile_email);
	           	 pd.put("email", "");
	            }else{
	              	 pd.put("email", mobile_email);
	           	 pd.put("phone", "");
	            }
		  	     PageData list = rService.query(pd);
			     Long ret= (Long) list.get("result");
			     System.out.println(ret);
			     if(ret==0){
			    	 result = JsonStringUtil.getJSONResult(StatusCode.ERROR_USER,"账号不存在","");
			     }else {
			   		rService.forget_pwd(pd);
			  		 result = JsonStringUtil.getJSONResult(StatusCode.SUCCESS,"密码修改成功","");
				}
	         }else {
	        	 result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"接口校验失败","");
					
			}

	
	} catch (Exception e) {
		result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"服务器内部错误","");
		logger.error(e.toString(),e);
		e.printStackTrace();
	}finally {
		return result.toString();
	}
	}
     
	  /*
	   * 验证码接口
	   */
		@SuppressWarnings("finally")
	    @RequestMapping(value=ClassNameUtil.sendCode,produces =HttpConfig.CONTENT_TYPE_UTF8)
		@ResponseBody
	 public String SendCode(HttpServletRequest request){
			Object result="";
	
	     try {
	    	 logBefore(logger, "开始调用验证码接口");
	  		 int code = (int)((Math.random()*9+1)*100000);
			 PageData pd = new PageData();
			 Object parameter = pd.getParameters(request);
			 JSONObject jObject = JSONObject.fromObject(parameter);
	         String key1 = new String(EncryptUtil.Base64decode(jObject.getString("key1")));
	         String key2 = new String(EncryptUtil.Base64decode(jObject.getString("key2")));
	         String access_key = new String(EncryptUtil.Base64decode(jObject.getString("access_key")));
	         String sult = Base64.check(key1, key2);
	         if (sult.equals(access_key)) {       //接口校验
	        	 logBefore(logger, "接口校验成功");
	    		 String mobile = new String(EncryptUtil.Base64decode(jObject.getString("mobile")));
	    	     String apikey = "67a0e0feef9fb4b684a806c7f477a418";
	             String text = "【UNION】 您的验证码是："+String.valueOf(code)+" (10分钟内有效,如非本人操作,请忽略)";
	    		 String result_sms= SendSms.sendSms(apikey, text, mobile);
	    		JSONObject jsonObject =JSONObject.fromObject(result_sms);
	    		if (jsonObject.getString("code").equals("0")) {
	    			result = JsonStringUtil.getJSONResult(StatusCode.SUCCESS,"短信验证码发送成功",code);
				}else{
					result = JsonStringUtil.getJSONResult(StatusCode.ERROR_USER,"发送失败","");
				}
	    		
	         }else{
	        	 result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"接口校验失败","");
	         }

		} catch (IOException e) {
			result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"服务器内部错误","");
			logger.error(e.toString(),e);
			e.printStackTrace();
		}finally {
			return result.toString();
		}
	 }
		
		
		/*
		 * 邮件接口
		 */
		@SuppressWarnings("finally")
	    @RequestMapping(value=ClassNameUtil.sendEmail,produces =HttpConfig.CONTENT_TYPE_UTF8)
		@ResponseBody
		public String SendEmail(HttpServletRequest request){
			Object result="";
	
			 int code = (int)((Math.random()*9+1)*100000);
			 try {
				 logBefore(logger, "开始调用邮件接口");
				 PageData pd = new PageData();
				 Object parameter = pd.getParameters(request);
				 JSONObject jObject = JSONObject.fromObject(parameter);
		         String key1 = new String(EncryptUtil.Base64decode(jObject.getString("key1")));
		         String key2 = new String(EncryptUtil.Base64decode(jObject.getString("key2")));
		         String access_key = new String(EncryptUtil.Base64decode(jObject.getString("access_key")));
		         String sult = Base64.check(key1, key2);
		         if (sult.equals(access_key)) {       //接口校验
		        	 logBefore(logger, "接口校验成功");
		        	 String email = new String(EncryptUtil.Base64decode(jObject.getString("email")));
		        	 String title = "联盟网";   //标题
		        	 String text ="您的邮件验证码是:"+String.valueOf(code)+"(10分钟内有效,如非本人操作,请忽略)";         //文本内容
		        	 SendSms.SendEmail(email, title, text);
		        	 result = JsonStringUtil.getJSONResult(StatusCode.SUCCESS,"邮箱验证码发送成功",code);
	
		         }else {
		        	 result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"接口校验失败","");
				}
		         
			} catch (Exception e) {
				result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"服务器内部错误","");
				logger.error(e.toString(),e);
				e.printStackTrace();
			}finally{
				return result.toString();
			}
		}
		
		
		
     
		/*
		 * 身份初级认证
		 */
	    @SuppressWarnings("finally")
		@RequestMapping(value=ClassNameUtil.primary,produces =HttpConfig.CONTENT_TYPE_UTF8)
		@ResponseBody
		public String Primary_certification(HttpServletRequest request) throws UnsupportedEncodingException{
	    	Object result ="";
	    	         
			    try {
			    	 logBefore(logger, "开始调用身份初级认证接口");
					 PageData pd = new PageData();
					 Object parameter = pd.getParameters(request);
					 JSONObject jObject = JSONObject.fromObject(parameter);
					 String user_id = new String(EncryptUtil.Base64decode(jObject.getString("user_id")));
			         String key1 = new String(EncryptUtil.Base64decode(jObject.getString("key1")));
			         String key2 = new String(EncryptUtil.Base64decode(jObject.getString("key2")));
			         String access_key = new String(EncryptUtil.Base64decode(jObject.getString("access_key")));
			         String sult = Base64.check(key1, key2);
			         if (sult.equals(access_key)) {       //接口校验
			        	 logBefore(logger, "接口校验成功");
			        	 String number = new String(EncryptUtil.Base64decode(jObject.getString("number")));
			        	 String name = new String(EncryptUtil.Base64decode(jObject.getString("name")));
			        	 String res = Authentication.primary(name, number);
			        	 JSONObject jsonObject = JSONObject.fromObject(res);
			        	 if (res!="" && jsonObject.getString("error_code").equals("0")) {
			        		 java.util.List<PageData> list = redis.getList(user_id,PageData.class);
				        	 for (PageData pageData : list) {
								   user_id = pageData.getString("USER_ID");
							}
			        		 JSONObject json = JSONObject.fromObject(jsonObject.getString("result"));
			        		 JSONObject jOb = JSONObject.fromObject(json.getString("details"));
			        		 pd.put("IDENTITY_ID", this.get32UUID());
			        		 pd.put("REAL_NAME", json.getString("realName"));
			        		 pd.put("CARD_NO", json.getString("cardNo"));
			        		 pd.put("BIRTH", jOb.getString("birth"));
			        		 pd.put("SEX", jOb.getString("sex"));
			        		 pd.put("ADDRES", jOb.getString("address"));
			        		 pd.put("USER_ID", user_id);
			        		 pd.put("NAME", json.getString("realName"));
			        		 rService.primary_certification(pd);
			        		 rService.up_name(pd);
			        		
			        		 result = JsonStringUtil.getJSONResult(StatusCode.SUCCESS,"认证成功",res);
						} else {
                           
                            result = JsonStringUtil.getJSONResult(StatusCode.ERROR_USER,"认证失败","");
						}
			        	 
			         }else{
			        	 result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"接口校验失败","");
			         }
	
			} catch (Exception e) {
				result= JsonStringUtil.getJSONResult(StatusCode.SYSTEM_ERROR,"服务器内部错误","");
				logger.error(e.toString(),e);
				e.printStackTrace();
				
			}finally {
				 return result.toString();
			}
		}

	    
	    
	    
	    
	public static void main(String[] args) throws Exception {
		

		
        
	}


	@RequestMapping("/basetest")
	public void basetest(HttpServletRequest request,HttpSession session) throws UnsupportedEncodingException, IOException{
			 session.setAttribute("USER", "888888");
			 session.setMaxInactiveInterval(-1);
			 
	}
	   
	@RequestMapping("/tset")
	  
	public void tset(HttpServletRequest request,HttpSession session) throws UnsupportedEncodingException, IOException{
		System.out.println(session.getAttribute("USER"));
			 
	}
	   
}
